package com.cskaoyan.day24.udp;


import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.util.Properties;


public class Receiver {
    public static void main(String[] args) throws IOException {

        InputStream in = ClassLoader.getSystemResourceAsStream("data.properties");
        // 字节输入流,包装成一个字符输入流

        InputStreamReader reader = new InputStreamReader(in);
        Properties properties = new Properties();
        properties.load(reader);



        DatagramSocket datagramSocket = new DatagramSocket(8888);

        while (true) {
            DatagramPacket receivePacket = new DatagramPacket(new byte[1024], 0, 1024);
            datagramSocket.receive(receivePacket);
            SocketAddress socketAddress = receivePacket.getSocketAddress();

            byte[] data = receivePacket.getData();
            int offset = receivePacket.getOffset();
            int length = receivePacket.getLength();
            String msg = new String(data, offset, length);
            System.out.println("来自于发送端:" + socketAddress + ", 他发送的消息是:" + msg);
            String ans;
            String value = properties.getProperty(msg);
            String value1 = properties.getProperty(msg);
            System.out.println(value1);
            if (value == null) {
                ans = "我没听懂你在说什么";
            } else {
                ans = value;
            }

            DatagramPacket sendPacket = UDPUtils.getSendPacket(ans, "127.0.0.1", 9999);
            datagramSocket.send(sendPacket);
        }


    }
}
